package com.example.demo1.service;

import com.example.demo1.common.AppResult;
import com.example.demo1.common.ResultCode;
import com.example.demo1.dao.OrganizationMapper;
import com.example.demo1.exception.ApplicationException;
import com.example.demo1.model.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
public class OrganizationService {
    @Autowired
    private OrganizationMapper organizationMapper;

    @Transactional
    public AppResult<Organization> create(Organization organization) {
        try {
            organization.validate();

            // 计算path
            String path;
            if (organization.getParentId() != null) {
                Organization parent = organizationMapper.findById(organization.getParentId());
                if (parent == null) {
                    throw new ApplicationException(ResultCode.PARENT_NOT_EXIST);
                }
                path = parent.getPath() + "PLACEHOLDER/"; // 先使用占位符
                organization.setLevel(parent.getLevel() + 1);
            } else {
                path = "PLACEHOLDER/";
                organization.setLevel(0);
            }

            // 先设置临时path
            organization.setPath(path);

            // 插入记录获取ID
            organizationMapper.insert(organization);

            // 更新为真实path
            String realPath = path.replace("PLACEHOLDER", organization.getId().toString());
            organization.setPath(realPath);
            organizationMapper.updatePathInfo(organization);

            return AppResult.success(organization);
        } catch (Exception e) {
            throw new ApplicationException(ResultCode.INTERNAL_ERROR, "创建组织失败: " + e.getMessage());
        }
    }

    @Transactional
    public AppResult<Organization> updateBasicInfo(Organization organization) {
        try {
            organization.validate();

            Organization existing = organizationMapper.findByIdForUpdate(organization.getId());
            if (existing == null) {
                throw new ApplicationException(ResultCode.ORGANIZATION_NOT_FOUND);
            }

            // 只更新名称
            existing.setName(organization.getName());
            organizationMapper.updateBasicInfo(existing);

            return AppResult.success(existing);
        } catch (IllegalArgumentException e) {
            throw new ApplicationException(ResultCode.BAD_REQUEST, e.getMessage());
        }
    }

    @Transactional
    public AppResult<Void> delete(Integer id) {
        Organization organization = organizationMapper.findByIdForUpdate(id);
        if (organization == null) {
            throw new ApplicationException(ResultCode.ORGANIZATION_NOT_FOUND);
        }

        // 检查是否有子节点
        List<Organization> children = organizationMapper.findByParentId(id);
        if (!children.isEmpty()) {
            throw new ApplicationException(ResultCode.HAS_CHILDREN);
        }

        organizationMapper.delete(id);
        return AppResult.success(null);
    }

    public AppResult<Organization> getById(Integer id) {
        Organization organization = organizationMapper.findById(id);
        if (organization == null) {
            throw new ApplicationException(ResultCode.ORGANIZATION_NOT_FOUND);
        }
        return AppResult.success(organization);
    }

    public AppResult<List<Organization>> getAll() {
        List<Organization> organizations = organizationMapper.findAll();
        return AppResult.success(organizations);
    }

    public AppResult<List<Organization>> getAncestors(Integer id) {
        Organization organization = organizationMapper.findById(id);
        if (organization == null) {
            throw new ApplicationException(ResultCode.ORGANIZATION_NOT_FOUND);
        }

        List<Organization> ancestors = organizationMapper.findAncestors(id, organization.getPath());
        return AppResult.success(ancestors);
    }

    public AppResult<List<Organization>> getDescendants(Integer id) {
        Organization organization = organizationMapper.findById(id);
        if (organization == null) {
            throw new ApplicationException(ResultCode.ORGANIZATION_NOT_FOUND);
        }

        List<Organization> descendants = organizationMapper.findDescendants(id, organization.getPath());
        return AppResult.success(descendants);
    }

    @Transactional
    public AppResult<Organization> move(Integer id, Integer newParentId) {
        try {
            // 获取并锁定当前节点
            Organization organization = organizationMapper.findByIdForUpdate(id);
            if (organization == null) {
                throw new ApplicationException(ResultCode.ORGANIZATION_NOT_FOUND);
            }

            // 检查移动是否有意义
            if ((newParentId == null && organization.getParentId() == null) ||
                    (newParentId != null && newParentId.equals(organization.getParentId()))) {
                return AppResult.success(organization);
            }

            // 处理新父节点
            Organization newParent = null;
            if (newParentId != null) {
                newParent = organizationMapper.findByIdForUpdate(newParentId);
                if (newParent == null) {
                    throw new ApplicationException(ResultCode.PARENT_NOT_EXIST);
                }

                // 检查循环引用
                if (newParent.getPath().contains(organization.getId() + "/")) {
                    throw new ApplicationException(ResultCode.CIRCULAR_REFERENCE);
                }
            }

            // 记录旧路径
            String oldPath = organization.getPath();

            // 计算新路径
            String newPath = newParentId == null ?
                    organization.getId() + "/" :
                    newParent.getPath() + organization.getId() + "/";

            // 验证新路径
            if (newPath.equals(oldPath)) {
                return AppResult.success(organization);
            }

            // 更新当前节点
            organization.setParentId(newParentId);
            organization.setPath(newPath);
            organization.setLevel(newParentId == null ? 0 : newParent.getLevel() + 1);
            organizationMapper.updatePathInfo(organization);

            // 批量更新所有子节点的path
            int levelDiff = (newParentId == null ? 0 : newParent.getLevel() + 1) - organization.getLevel();
            organizationMapper.updateDescendantsPaths(oldPath, newPath, levelDiff);

            return AppResult.success(organization);
        } catch (Exception e) {
            throw new ApplicationException(ResultCode.INTERNAL_ERROR, "移动组织失败: " + e.getMessage());
        }
    }

    // 私有方法：验证路径完整性
    private void validatePathIntegrity(Organization organization) {
        if (organization.getPath() == null) {
            throw new IllegalArgumentException("路径不能为null");
        }

        String[] ids = organization.getPath().split("/");
        for (String idStr : ids) {
            if (!idStr.isEmpty()) {
                try {
                    int id = Integer.parseInt(idStr);
                    if (id <= 0) {
                        throw new IllegalArgumentException("路径中包含无效的ID: " + idStr);
                    }
                    // 最后一个ID应该是当前组织自己的ID
                    if (id == organization.getId()) continue;

                    // 检查路径中的每个节点是否存在
                    if (organizationMapper.findById(id) == null) {
                        throw new IllegalArgumentException("路径中包含不存在的节点ID: " + id);
                    }
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("路径中包含非数字ID: " + idStr);
                }
            }
        }
    }
//    @Transactional
//    public AppResult<Void> deleteOrganizationWithChildren(Integer id) {
//        // 1. 检查组织是否存在
//        Organization organization = organizationMapper.findById(id);
//        if (organization == null) {
//            throw new ApplicationException(ResultCode.ORGANIZATION_NOT_FOUND);
//        }
//
//        // 2. 获取所有要删除的组织ID（包括自身和所有后代）
//        List<Integer> idsToDelete = new ArrayList<>();
//        idsToDelete.add(id); // 添加自身ID
//
//        // 获取所有后代组织ID
//        List<Organization> descendants = organizationMapper.findDescendants(id, organization.getPath());
//        descendants.forEach(descendant -> idsToDelete.add(descendant.getId()));
//
//        // 3. 执行批量删除
//        if (!idsToDelete.isEmpty()) {
//            organizationMapper.batchDeleteOrganizations(idsToDelete);
//        }
//
//        return AppResult.success(null);
//    }
}
